package com.java.common.pay.wxpay.utils;

import com.thoughtworks.xstream.XStream;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.xml.sax.InputSource;

import javax.servlet.http.HttpServletRequest;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class XMLTool {

	public static void main(String[] args) {
		Document document = strToXMLDocment("<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[发放成功.]]></return_msg><result_code><![CDATA[SUCCESS]]></result_code><err_code><![CDATA[0]]></err_code><err_code_des><![CDATA[发放成功.]]></err_code_des><mch_billno><![CDATA[0010010404201411170000046545]]></mch_billno><mch_id>10010404</mch_id><wxappid><![CDATA[wx6fa7e3bab7e15415]]></wxappid><re_openid><![CDATA[onqOjjmM1tad-3ROpncN-yUfa6uI]]></re_openid><total_amount>1</total_amount></xml> ");
		System.out.println(document.getRootElement().elementText("err_code"));

	}
	/**
	 * 方法名：mapToXML
	 * 详述：把map转成xml字符串
	 *
	 * @param map
	 * @return
	 */
	public static String mapToXML(Map map) {
		if (map != null) {
			Element root = DocumentHelper.createElement("xml");
			Document document = DocumentHelper.createDocument(root);
			Set<String> set = map.keySet();
			for (String key : set) {
				if (map.get(key) != null) {
					root.addElement(key).addText(String.valueOf(map.get(key)));
				}
			}
			return document.asXML();
		}
		return "";
	}
	
	/**
	 * 方法名：objToXML
	 * 详述：把实体转成xml格式字符串
	 * @param obj
	 * @return String
	 */
	public static String objToXML(Object obj){
		XStream xstream = new XStream();
		xstream.alias("xml", obj.getClass());
		return xstream.toXML(obj).replace("__", "_");
	}
	
	
	/**
	 * 方法名：getDocumentBuilder
	 * 详述：创建DocumentBuilder对象
	 * @return DocumentBuilder
	 */
	public static DocumentBuilder getDocumentBuilder() {
		// 获得dom解析器工厂（工作的作用是用于创建具体的解析器）
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		// 获得具体的dom解析器
		try {
			return dbf.newDocumentBuilder();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 方法名：XMLToMap
	 * 详述：把xml字符串封装到Map中
	 * @param request
	 * @return
	 * @throws Exception
	 */
	public static Map<String,String> XMLToMap(HttpServletRequest request){
		try{
			Map<String,String> map = new HashMap<String, String>();
			SAXReader reader = new SAXReader();
			InputStream ins = request.getInputStream();
			Document doc = reader.read(ins);
			Element root = doc.getRootElement();
			List<Element> list = root.elements();
			for(Element e : list){
				map.put(e.getName(), e.getText());
			}
			ins.close();
			return map;
		}catch(DocumentException e){
			throw new RuntimeException(e.getMessage());
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		return null;
	}

	/**
	 * 方法名：XMLToMap
	 * 详述：把xml字符串封装到Map中
	 * @param xml
	 * @return
	 */
	public static Map<String,String> XMLToMap(String xml){
		try{
			Map<String,String> map = new HashMap<String, String>();
			Document doc = DocumentHelper.parseText(xml);
			Element root = doc.getRootElement();
			List<Element> list = root.elements();
			for(Element e : list){
				map.put(e.getName(), e.getText());
			}
			return map;
		}catch(DocumentException e){
			e.printStackTrace();
		}
		return null;
	}

	/*public static org.w3c.dom.Document parseXMLDocument(String xmlString) {
        if (xmlString == null) {  
            throw new IllegalArgumentException();  
        }  
        try {  
            return newDocumentBuilder().parse(new InputSource(new StringReader(xmlString)));
        } catch (Exception e) {  
            throw new RuntimeException(e.getMessage());  
        }  
    }*/

	/**
	 * 方法名：strToXMLDocment
	 * 详述：把String转成Document对象
	 * @param xmlStr
	 * @return Document
	 */
	public static Document strToXMLDocment(String xmlStr) {
		Document document = null;
		try {
			document = DocumentHelper.parseText(xmlStr);
		} catch (DocumentException e) {
			throw new RuntimeException(e.getMessage());
		}
		return document;
	}
	
	/**
	 * 方法名：newDocumentBuilder
	 * 详述：创建一个DocumentBuilder实例
	 * @return
	 * @throws ParserConfigurationException DocumentBuilder
	 */
	public static DocumentBuilder newDocumentBuilder() throws ParserConfigurationException {  
		return newDocumentBuilderFactory().newDocumentBuilder();  
	} 

	/**
	 * 方法名：newDocumentBuilderFactory
	 * 详述：创建一个DocumentBuilderFactory实例
	 * @return DocumentBuilderFactory
	 */
	public static DocumentBuilderFactory newDocumentBuilderFactory() {  
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();  
        dbf.setNamespaceAware(true);  
        return dbf;  
    } 
}
